using MediatR;
using Microsoft.AspNetCore.Mvc;
using RabbitTraceability.Api.Applications.Command;
using ErrorCode;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
using Domain;
using Infrastructure;
using System.Security.Cryptography;
using System.Text;
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using RabbitTraceability.Api.Dtos.Request;
using RabbitTraceability.Api.Dtos.Response;
using Infrastructure.Redis;

namespace RabbitTraceability.Api.Controllers
{
    /// <summary>
    /// 用户控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class UserController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly ILogger<UserController> _logger;
        private readonly IRepository<UserInfo> _userRepository;
        private readonly IRedisHelper _redisHelper;
        private const string CAPTCHA_GROUP = "Captcha:String:";

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mediator">中介者</param>
        /// <param name="logger">日志记录器</param>
        /// <param name="userRepository">用户仓储</param>
        /// <param name="redisHelper">Redis帮助类</param>
        public UserController(IMediator mediator, ILogger<UserController> logger, 
            IRepository<UserInfo> userRepository, IRedisHelper redisHelper)
        {
            _mediator = mediator;
            _logger = logger;
            _userRepository = userRepository;
            _redisHelper = redisHelper;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="request">登录请求</param>
        /// <returns>JWT令牌</returns>
        [HttpPost]
        public async Task<ApiResult<string>> Login(UserLoginRequestDto request)
        {
            _logger.LogInformation("接收到用户登录请求: {@Username}", request.Username);

            try
            {
                // 直接将请求转发到命令处理器
                var command = new UserLoginCommand
                {
                    Username = request.Username,
                    Password = request.Password,
                    //CaptchaGuid = request.CaptchaGuid,
                    //CaptchaCode = request.CaptchaCode
                };
                
                var token = await _mediator.Send(command);
                return ApiResult<string>.SuccessWithData(token);
            }
            catch (ApiException ex)
            {
                return ApiResult<string>.Fail(ex.Message, ex.Code);
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, "登录过程中发生错误: {Message}", ex.Message);
                return ApiResult<string>.Fail("登录失败，请稍后再试", ResultCode.服务器错误);
            }
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="request">注册请求</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        public async Task<ApiResult> Register([FromBody] UserRegisterRequestDto request)
        {


            try
            {
                // 检查用户名是否已存在
                var existingUsers = _userRepository.GetAll().FirstOrDefault(u => u.Username == request.Username);
                if (existingUsers != null)
                {
                    return ApiResult.Fail("用户名已存在", ResultCode.UserNameExists);
                }

                // 创建新用户
                var user = new UserInfo
                {
                    Username = request.Username,
                    Password = request.Password, // 实际应用中应该哈希密码
                    RealName = request.RealName ?? string.Empty, // 确保不为null
                    Email = request.Email ?? string.Empty, // 确保不为null
                    Gender = request.Gender,
                    Status = 1, // 默认启用
                    CreatedBy = "system"
                };

                await _userRepository.AddAsync(user);
                _logger.LogInformation("用户注册成功: {Username}", request.Username);

                return ApiResult.Success("注册成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "用户注册过程中发生错误: {Message}", ex.Message);
                return ApiResult.Fail("注册失败，请稍后再试", ResultCode.服务器错误);
            }
        }
    }
}